/*
 * @lc app=leetcode.cn id=394 lang=typescript
 *
 * [394] 字符串解码
 */

// @lc code=start
var decodeString = function (s: string): string {
  let result = '';

  let i = 0;
  while (i < s.length) {
    if (/[a-zA-Z]/.test(s[i])) {
      result += s[i++];
    } else {
      let sum = 0;
      while (/\d/.test(s[i])) {
        sum = sum * 10 + Number(s[i]);
        i++;
      }
      i++;
      let l = i;
      let r = i;
      let cnt = 1;
      // 找到方括号的左右下标
      while (cnt) {
        r++;
        if (s[r] === '[') cnt++;
        else if (s[r] === ']') cnt--;
      }
      // 递归处理方括号内的字符串
      let temp = decodeString(s.substring(l, r));
      while (sum--) result += temp;
      i = r + 1;
    }
  }
  return result;
};
// @lc code=end
